package com.hele.sts.action.admin;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.hele.sts.dao.*;
import com.hele.sts.pub.Constants;
import com.hele.sts.pub.SelectOption;
import com.hele.sts.pub.SpringContextHolder;
import com.hele.sts.pub.encrypt.BCryptPasswordEncoder;
import org.apache.commons.lang.time.DateUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Administrator
 */
public class AdminUserLoginAction
  implements Action
{

    @Autowired
    private XtUserLoginDao xtUserLoginDao;

    @Autowired
    private AdminUserPermDao adminUserPermDao;

    @Autowired
    private XtLogDao xtLogDao;

  @Override
  public String execute()
    throws Exception
  {
      if(action==null){
          action = "adminLogin";
          return "init";
      }
      if("initPassword".equals(action)){
          List userList = UserDao.load(null,null);
          BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
          for(int i=0;i<userList.size();i++){
              User user = (User)userList.get(i);
              String oldPassword = user.getEfPassword();
              if(oldPassword!=null && oldPassword.length()<20){
                  String newPassword = passwordEncoder.encode(oldPassword);
                  user.setEfPassword(newPassword);
                  int ret = UserDao.updatePassword(user);
              }
          }
          this.tipInfo = "所有密码初始化完成";
          return "ajax";
      }
      if("initPasswordForDacx".equals(action)){
          List qUserList = QUserDao.loadList();
//          List userList = UserDao.load(null,null);
          BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
          for(int i=0;i<qUserList.size();i++){
              QUser user = (QUser)qUserList.get(i);
              String oldPassword = user.getPasswd();
              if(oldPassword!=null && oldPassword.length()<20){
                  String newPassword = passwordEncoder.encode(oldPassword);
                  user.setPasswd(newPassword);
                  QUserDao.updatePassword(user.getUserId(),newPassword);
              }
          }
          this.tipInfo = "所有查询系统的密码初始化完成";
          return "ajax";
      }
    if ("login".equalsIgnoreCase(this.action)) {
      return login();
    }

    if ("logout".equalsIgnoreCase(this.action)) {
      return logout();
    }
    String sslString = ServletActionContext.getRequest().getHeader("From");
    logger.debug(sslString);
    if ((sslString != null) && (sslString.length() > 0))
    {
      sslString = new String(sslString.getBytes("ISO8859_1"), "GBK");
      String[] ss = sslString.split(":");
      String userName = ss[2];
      logger.debug(userName);
      User user = UserDao.load(userName);
      logger.debug(user + "user");
      if (user == null)
      {
        logger.debug("数据不存在。");
        return "error";
      }
      ActionContext ctx = ActionContext.getContext();
      Map session = ctx.getSession();
      session.put("AdminUser.loginName", user.getUserName());
      session.put("AdminUser", user);
    }
    return "success";
  }

  public String login(){
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    User user = (User)session.get("AdminUser");

    if(user!=null){
      return "success";
    }
      if (username == null) {
          this.tipInfo = "请输入用户名！";
          return "login";
      }
      if (password == null) {
          this.tipInfo = "请输入密码！";
          return "login";
      }
      XtUserLoginDao xtUserLoginDao = SpringContextHolder.getBean(XtUserLoginDao.class);
      XtLogDao xtLogDao = SpringContextHolder.getBean(XtLogDao.class);
      XtUserLogin xtUserLogin = xtUserLoginDao.queryByUsername(username);
      int loginErrorCount = 0;
      if(xtUserLogin!=null){
          int loginState = xtUserLogin.getLoginState();
          if(Constants.LOGIN_STATE_LOCKED==loginState){
              Date allowLoginTime = xtUserLogin.getAllowLoginTime();
              if(allowLoginTime!=null && new Date().before(allowLoginTime)){
                  tipInfo = "登录错误次数太多，暂停使用";
                    return "login";
                  //return "login.jsp";
              }else{
                  //晚于允许访问时间，允许继续尝试，或允许时间为空
              }
          }
          loginErrorCount = xtUserLogin.getLoginErrorCount();
          if(loginErrorCount>= Constants.USER_LOCK_TIMES ){

          }
      }else {

      }

      //user = UserDao.login(username,password);
      user = UserDao.load(username);
      if(user==null){
          tipInfo = "请输入正确的用户名和密码！";
          return "login";
      }
      String dbPass = user.getEfPassword();
      BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
      boolean matched = passwordEncoder.matches(password,dbPass);


      if(matched){

          xtLogDao.insertLog("业务日志","后管登录成功",user.getUserId(),username,"成功","用户："+username,"admin/login.jsp");
          if(xtUserLogin==null){
              xtUserLogin = new XtUserLogin();
              xtUserLogin.setUsername(username);
              xtUserLogin.setLoginErrorCount(0);
              xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOGIN);
              xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
              xtUserLoginDao.insert(xtUserLogin);
          }else {
              xtUserLogin.setLoginErrorCount(0);
              xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOGIN);
              xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
              xtUserLoginDao.update(xtUserLogin);
          }

          String djjg = user.getDjjg();
          session.put("AdminUser.loginName", user.getUserName());
          session.put("AdminUser.djjg",djjg);
          session.put("AdminUser.gxdw",user.getGxdwdm());
          String djjgmc = null;
          try {
              djjgmc = SelectOption.getCodeVal("bm_djjg", djjg);
          } catch (SQLException e) {
              logger.error("djjg 查询出错",e);
          }
          session.put("djjgmc",djjgmc);
          session.put("AdminUser",user);

          List<XtRole> userXtRoleList = adminUserPermDao.getRoleList(user.getUserId());
          session.put("adminRoleList", userXtRoleList);
          List<XtMenu> userXtMenuList = adminUserPermDao.getMenuList(user.getUserId());
          session.put("adminMenuList", userXtMenuList);
          AdminUser adminUser = new AdminUser();
          adminUser.setUser(user);
          adminUser.setXtMenuList(userXtMenuList);
          adminUser.setXtRoleList(userXtRoleList);
          session.put("myAdminUser",adminUser);
          return "success";
      } else {
          tipInfo = "请输入正确的用户名和密码！";
          if(xtUserLogin==null){
              xtUserLogin = new XtUserLogin();
              xtUserLogin.setUsername(username);
              xtUserLogin.setLoginErrorCount(1);
              xtUserLogin.setLoginState(Constants.LOGIN_STATE_NOT_LOGIN);
              xtUserLogin.setLastLoginTime(new Date(System.currentTimeMillis()));
              xtUserLoginDao.insert(xtUserLogin);
          }else {
              loginErrorCount = xtUserLogin.getLoginErrorCount();
              loginErrorCount += 1;
              if(loginErrorCount>=Constants.USER_LOCK_TIMES){
                  xtUserLogin.setLoginState(Constants.LOGIN_STATE_LOCKED);
                  //允许登录时间为从当前服务器时间开始
                  Date allowData = DateUtils.addMinutes(new Date(System.currentTimeMillis()),Constants.LOGIN_LOCKED_TIME);
                  xtUserLogin.setAllowLoginTime(allowData);
                  tipInfo = "您输入的错误次数太多，请稍候再试！";
              }
              if(loginErrorCount>= Constants.USER_VERIFY_TIMES){
                  //需要显示验证码
                  // showCaptcha = true;
              }else{

              }
              xtUserLogin.setLoginErrorCount(loginErrorCount);
              xtUserLoginDao.update(xtUserLogin);
          }//end of xtUserLogin
          xtLogDao.insertLog("业务日志","后管登录失败","",username,"成功","用户："+username,"admin/login.jsp");

      }//end of user==null
    return "login";
  }
  
  public String logout()
    throws Exception
  {
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    User user = (User)session.get("AdminUser");
    session.remove("AdminUser.loginName");
    session.remove("AdminUser");
    if(user!=null){
        xtLogDao.insertLog("业务日志","后管退出成功",user.getUserId(),user.getUserName(),"成功","用户："+user.getUserName()+"退出","admin/logout.jsp");
    }

      return "admin_logout";
  }
  
  public String getErrorInfo()
  {
    return this.errorInfo;
  }
  
  public void setErrorInfo(String errorInfo)
  {
    this.errorInfo = errorInfo;
  }
  
  public String getLoginName()
  {
    return this.loginName;
  }
  
  public void setLoginName(String loginName)
  {
    this.loginName = loginName;
  }
  
  public String getLoginPass()
  {
    return this.loginPass;
  }
  
  public void setLoginPass(String loginPass)
  {
    this.loginPass = loginPass;
  }
  
  public int getLoginType()
  {
    return this.loginType;
  }
  
  public void setLoginType(int loginType)
  {
    this.loginType = loginType;
  }
  
  public String getCertSerial()
  {
    return this.certSerial;
  }
  
  public void setCertSerial(String certSerial)
  {
    this.certSerial = certSerial;
  }
  
  public String getAction()
  {
    return this.action;
  }
  
  public void setAction(String action)
  {
    this.action = action;
  }
  
  static Logger logger = LoggerFactory.getLogger(AdminUserLoginAction.class);
  String action;
  int loginType;
  String loginName;
  String loginPass;
  String certSerial;
  String errorInfo;
  String username;
  String password;
  String tipInfo;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTipInfo() {
        return tipInfo;
    }

    public void setTipInfo(String tipInfo) {
        this.tipInfo = tipInfo;
    }
}
